package com.golte.dataform.analysis.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.golte.common.GlobalResponse;
import com.golte.dataform.analysis.common.JwtUtil;
import com.golte.dataform.analysis.service.ReportService;
import com.golte.dataform.analysis.vo.response.CheckResp;
import com.golte.dataform.analysis.vo.response.Industy;
import com.golte.utils.RedisUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: sm
 * @Date: 2021/3/6
 */
@RestController
@Slf4j
@RequestMapping("/report")
@Api(value = "星选报表", description = "星选报表")
public class CheckinController {

    private static final String INDUSTTRY_PREFIX = "FXREPORT:";
    private static final String INDUSTTRY_BRAND = INDUSTTRY_PREFIX + "INDUSTTRY_BRAND";

    @Autowired
    private ReportService reportService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${app.key}")
    private String secretKey;

    @GetMapping("/check")
    @ApiOperation("check in")
    public GlobalResponse<CheckResp> getToken(@RequestParam("r") Integer roleId, @RequestParam("t") Long timestamp,
                                              @RequestParam("i") String industryIds, @RequestParam("b") String brandIds, @RequestParam("sign") String sign) {

        log.info("CheckinController.getToken: roleId=[{}], timestamp=[{}], industryIds=[{}], brandIds=[{}], sign=[{}]", roleId, timestamp, industryIds, brandIds, sign);

//        String token = IdUtil.randomUUID();
        TreeMap treeMap = new TreeMap() {{
            put("r", roleId);
            put("t", timestamp);
            put("i", industryIds);
            put("b", brandIds);
        }};
        if((System.currentTimeMillis() - timestamp ) > 1*60*1000){
            return GlobalResponse.fail("地址已失效");
        }

        List<Integer> is = Arrays.stream(industryIds.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<Integer> bs = Arrays.stream(brandIds.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        Map dataMap = new HashMap() {{
            put("r", roleId);
            put("i", is);
            put("b", bs);
        }};
        String token = jwtUtil.createToken(dataMap);
        String sig = createSign(treeMap, secretKey);
        log.info("sign:{}", sig);
        // 校验
        if (!sign.equals(sig)) {
            return GlobalResponse.fail("校验出错");
        }

        Object data = null;
        List<Industy> list = null;
        if (1 == roleId) {
//            data = getIndustryAndBrand();
//            return GlobalResponse.ok(JSON.parseArray(data.toString()));
            list = reportService.getAllIndustryAndBrand();
        } else {
            list = reportService.getIndustryAndBrand(industryIds, brandIds);
        }

        CheckResp resp = new CheckResp();
        resp.setToken(token);
        resp.setList(list);

        return GlobalResponse.ok(resp);

    }

    public String getIndustryAndBrand() {
        Object data = redisUtil.get(INDUSTTRY_BRAND);
        if (null == data) {
            List<Industy> list = reportService.getAllIndustryAndBrand();
            data = JSON.toJSONString(list);
            redisUtil.set(INDUSTTRY_BRAND, data, 3600);
        }
        return data.toString();

    }

    /**
     * 把排序后的结果按照【参数+参数值 + &】的方式拼接，再加上secretKey=secretKeyValue
     * 拼装好的字符串按MD5(p1=v1&p2=v2&p3=v3&secretKey=secretKeyValue)进行md5加密后，转小写
     *
     * @param parameters
     * @param secretKey
     * @return
     */
    private static String createSign(Map<String, Object> parameters, String secretKey) {
        //拼接签名的字符串
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.append("secretKey=" + secretKey);
        // 注意sign转为大写
        return SecureUtil.md5(sb.toString());
    }


}
